package com.galaxy.service.shiro;

import com.galaxy.commom.base.jwt.JwtToken;
import com.galaxy.commom.base.utils.JwtUtil;
import com.galaxy.commom.base.utils.Md5EncryptUtil;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

/**
 * 用户信息和token的匹配
 * @author caijinbang
 * @date 2018/10/28 01:42
 */
public class CredentialsMatcher extends SimpleCredentialsMatcher {

  /**
   * 用户信息和token的匹配
   * @param token
   * @param info
   * @return
   */
  @Override
  public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    JwtToken jwtToken = (JwtToken) token;
    Object accountCredentials = getCredentials(info);
    if(jwtToken.getPassword()!=null){
      Object tokenCredentials = Md5EncryptUtil.string2MD5(String.valueOf(
          jwtToken.getPassword())+jwtToken.getUsername());
      if(!accountCredentials.equals(tokenCredentials)){
        throw new DisabledAccountException("密码不正确！");
      }
    }else{
      boolean verify = JwtUtil.verify(jwtToken.getToken(), jwtToken.getUsername(), accountCredentials.toString());
      if(!verify){
        throw new DisabledAccountException("verifyFail");
      }
    }
    return true;
  }
}
